package com.ydlclass.loadbalancer;

import com.ydlclass.YrpcBootstrap;
import com.ydlclass.discovery.Registry;
import com.ydlclass.loadbalancer.SelectorImpl.RoundRobinSelector;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抽象模版，公共的都在这里面，不同的交给子类去实现
 * @Author duWenJian
 * @Date 2024/2/25 20:51
 * @Version 1.0
 */
@Slf4j
public abstract class AbstractLoadBalance implements LoadBalance{

    public static Map<String,Selector> cache = new ConcurrentHashMap<>(8);

    @Override
    public InetSocketAddress selectServiceAddress(String serviceName , String group) {

        Selector selector = cache.get(serviceName);
        if (selector == null){
            // 对于这个负载均衡器，内部应该维护一个服务列表作为缓存，
            List<InetSocketAddress> SocketAddressList = YrpcBootstrap.getInstance().getConfiguration().getRegistryConfig().getRegistry().lookup(serviceName, group);
            // 提供一些算法负责选取合适的节点
            selector = getSelector(SocketAddressList);
        }
        cache.put(serviceName,selector);
        return selector.getNext();
    }

    @Override
    public void reLoadBalance(String serviceName, List<InetSocketAddress> inetSocketAddressList) {
        cache.put(serviceName,getSelector(inetSocketAddressList));
    }

    /**
     * 实现不同的负载算法
     * @param socketAddressList
     * @return
     */
    protected abstract Selector getSelector(List<InetSocketAddress> socketAddressList);

}
